"""
基于物品相似度的协同过滤算法
"""

"""
1.淘宝获取销量最高的网红商品，
2.关键词：网红 微娅推荐 
3.价格：3 - 10
4.销量从高到低
"""

import requests
from bs4 import BeautifulSoup as bf
import pandas as pd
from  lxml import etree
import pandas as pd

# page = requests.get("https://www.myagric.com/article/p-4118-------------1.html").text
# obj = bf(page,'html.parser')
# print("获取库存导航地址")
# aa = obj.find("ul",{"class":"select-breed clearfix zhoubao"}).findAll('li')
# print(aa)

# page = requests.get("https://www.taobao.com/")
#
# print(page.text)

"""

from selenium import webdriver
import logging
import time
from selenium.common.exceptions import NoSuchElementException, WebDriverException
from retrying import retry
from selenium.webdriver import ActionChains
 
import pyautogui
 
pyautogui.PAUSE = 0.5
 
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
 
 
class TaoBao(object):
    def __init__(self):
        super(TaoBao, self).__init__()
        # self.browser = webdriver.Chrome("path\to\your\chromedriver.exe")
        self.browser = webdriver.Chrome()
        # 最大化窗口
        self.browser.maximize_window()
        self.browser.implicitly_wait(5)
        self.domain = 'http://www.taobao.com'
        self.action_chains = ActionChains(self.browser)
 
    def login(self, username, password):
        while True:
            self.browser.get(self.domain)
            time.sleep(1)
 
            # 会xpath可以简化这几步
            # self.browser.find_element_by_class_name('h').click()
            # self.browser.find_element_by_id('fm-login-id').send_keys(username)
            # self.browser.find_element_by_id('fm-login-password').send_keys(password)
            self.browser.find_element_by_xpath('//*[@id="J_SiteNavLogin"]/div[1]/div[1]/a[1]').click()
            self.browser.find_element_by_xpath('//*[@id="fm-login-id"]').send_keys(username)
            self.browser.find_element_by_xpath('//*[@id="fm-login-password"]').send_keys(password)
            time.sleep(1)
 
            try:
                # 出现验证码，滑动验证
                slider = self.browser.find_element_by_xpath("//span[contains(@class, 'btn_slide')]")
                if slider.is_displayed():
                    # 拖拽滑块
                    self.action_chains.drag_and_drop_by_offset(slider, 258, 0).perform()
                    time.sleep(0.5)
                    # 释放滑块，相当于点击拖拽之后的释放鼠标
                    self.action_chains.release().perform()
            except (NoSuchElementException, WebDriverException):
                logger.info('未出现登录验证码')
 
            # 会xpath可以简化点击登陆按钮，但都无法登录，需要使用 pyautogui 完成点击事件
            # self.browser.find_element_by_class_name('password-login').click()
            # self.browser.find_element_by_xpath('//*[@id="login-form"]/div[4]/button').click()
            # 图片地址
            coords = pyautogui.locateOnScreen('./1.png')
            x, y = pyautogui.center(coords)
            pyautogui.leftClick(x, y)
 
            nickname = self.get_nickname()
            if nickname:
                logger.info('登录成功，呢称为:' + nickname)
                break
            logger.debug('登录出错，5s后继续登录')
            time.sleep(5)
 
    def get_nickname(self):
        self.browser.get(self.domain)
        time.sleep(0.5)
        try:
            return self.browser.find_element_by_class_name('site-nav-user').text
        except NoSuchElementException:

if __name__ == '__main__':
    # 填入自己的用户名，密码
    username = '淘宝用户名'
    password = '淘宝密码'
    tb = TaoBao()
    tb.login(username, password)

"""

# page = '‪C:/Users/wx-5421/Downloads/weiya.html'
# aaa = open('‪C:/Users/wx-5421/Downloads/weiya.html',encoding='utf-8')
# print(aaa)
# soup=bf(open(page,encoding='utf-8'),features='html.parser')

with open(r'C:\Users\wx-5421\Downloads\taobao1.html','r',encoding='utf-8') as f:
    page = bf(f,features='html.parser')


store_sales = []
store_price = []
store_desc = []

print("商品销量为")
count = page.findAll(name='div',attrs={"class":"deal-cnt"})
for i in range(0,len(count)):
    store_sales.append(count[i].text)


print("商品价格")
price = page.findAll(name='div',attrs={"class":"price g_price g_price-highlight"})
for i in range(0,len(price)):
    store_price.append(price[i].text)


name = page.findAll(name="div",attrs={"class":"row row-2 title"})
for i in range(0,len(name)):
    store_desc.append(name[i].text)

print(store_sales[0:19])
print(store_price[0:19])
print(store_desc[0:19])

store = {"store_sales":store_sales,"store_price":store_price,"store_desc":store_desc}
goods = pd.DataFrame(store)
print(goods)



"""
class
1.<div class="price g_price g_price-highlight"> strong 获取价格
2.<div class="deal-cnt"> 收货人数
3.<div class="row row-2 title"> .a >href 商品链接 .span 
2. 获取产品名称,可以使用js代码， class = row row-2 title innerText的值

"""

# page1 = etree.parse(r'C:\Users\wx-5421\Downloads\taobao1.html', etree.HTMLParser())
# result = page1.xpath('//input')
# print("result",result)

